<template>
  <el-tree-select
    v-model="modelValue"
    popper-class="remote-select-box"
    :data="treeData"
    :props="treeProps"
    :filterable="filterable"
    :placeholder="calcPlaceholder"
    @change="handleChange"
    multiple
  />
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useDisabled } from 'element-plus';
import api from '@/http/api';

const emit = defineEmits(['change']);
const modelValue = defineModel();
const props = defineProps({
  dataUrl: String,
  filterable: {
    type: Boolean,
    default: true
  },
  placeholder: {
    type: String,
    default: '--请选择--'
  },
});

const inputDisabled = useDisabled();
const treeData = ref([]);
const treeProps = ref({
  children: 'children',
  value: 'id',
  label: 'text',
  disabled: (data) => !(data.children && data.children.length > 0) && data.type !== 'model'
});

const handleChange = () => {
  emit('change');
};

const calcPlaceholder = computed(() => {
  return inputDisabled.value ? ' ' : props.placeholder;
});

const loadData = (params) => {
  api.post(props.dataUrl, params).then(res => {
    treeData.value = res.data.children || [];
  });
};

onMounted(() => {
  loadData();
});
</script>

<style>
.remote-select-box .el-select-dropdown__wrap {
  max-height: 70vh;
  text-align: left;
}
</style>